package com.example.javapracticaltraining.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javapracticaltraining.entity.R;
import com.example.javapracticaltraining.entity.pojo.MedicalStaff;
import com.example.javapracticaltraining.service.MedicalStaffService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 医护人员管理控制器
 */
@RestController
@RequestMapping("/medicalstaff")
@Tag(name = "医护人员管理", description = "医护人员的增删改查操作")
public class MedicalStaffController {

    @Autowired
    private MedicalStaffService medicalStaffService;

    /**
     * 获取所有医护人员
     * @return 医护人员列表
     */
    @Operation(summary = "获取所有医护人员", description = "返回系统中所有医护人员的列表")
    @ApiResponse(responseCode = "200", description = "成功获取医护人员列表")
    @GetMapping
    public R<List<MedicalStaff>> getAllMedicalStaff() {
        List<MedicalStaff> staffList = medicalStaffService.list();
        return R.success(staffList);
    }

    /**
     * 分页获取医护人员
     * @param page 页码
     * @param pageSize 每页大小
     * @param name 姓名（可选，用于筛选）
     * @param position 职位（可选，用于筛选）
     * @return 分页后的医护人员列表
     */
    @Operation(summary = "分页获取医护人员", description = "根据条件分页查询医护人员，支持按姓名和职位筛选")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取分页医护人员列表")
    })
    @GetMapping("/page")
    public R<Page<MedicalStaff>> getMedicalStaffByPage(
            @Parameter(description = "页码，默认为1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页记录数，默认为10") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "姓名，可选参数，支持模糊查询") String name,
            @Parameter(description = "职位，可选参数，精确匹配") String position) {

        Page<MedicalStaff> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<MedicalStaff> queryWrapper = new LambdaQueryWrapper<>();

        if (name != null && !name.isEmpty()) {
            queryWrapper.like(MedicalStaff::getName, name);
        }

        if (position != null && !position.isEmpty()) {
            queryWrapper.eq(MedicalStaff::getPosition, position);
        }

        // 默认按在职状态和姓名排序
        queryWrapper.orderByDesc(MedicalStaff::getStatus)
                   .orderByAsc(MedicalStaff::getName);

        medicalStaffService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据ID获取医护人员
     * @param staffId 医护人员ID
     * @return 医护人员信息
     */
    @Operation(summary = "根据ID获取医护人员", description = "根据医护人员ID获取医护人员详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取医护人员信息"),
        @ApiResponse(responseCode = "404", description = "未找到该医护人员")
    })
    @GetMapping("/{staffId}")
    public R<MedicalStaff> getMedicalStaff(@Parameter(description = "医护人员ID") @PathVariable Integer staffId) {
        MedicalStaff staff = medicalStaffService.getById(staffId);
        if (staff != null) {
            return R.success(staff);
        }
        return R.failure(404, "未找到该医护人员");
    }

    /**
     * 添加新的医护人员
     * @param staff 医护人员信息
     * @return 操作结果
     */
    @Operation(summary = "添加医护人员", description = "创建新的医护人员记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "医护人员添加成功"),
        @ApiResponse(responseCode = "400", description = "已存在相同手机号的医护人员")
    })
    @PostMapping
    public R<String> addMedicalStaff(@RequestBody MedicalStaff staff) {
        // 设置默认值
        if (staff.getStatus() == null) {
            staff.setStatus(1); // 默认在职
        }

        staff.setHireDate(LocalDateTime.now());

        // 检查是否已存在相同手机号的医护人员
        LambdaQueryWrapper<MedicalStaff> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MedicalStaff::getPhone, staff.getPhone());
        MedicalStaff existingStaff = medicalStaffService.getOne(queryWrapper);

        if (existingStaff != null) {
            return R.failure(400, "已存在相同手机号的医护人员");
        }

        medicalStaffService.save(staff);
        return R.success("医护人员添加成功");
    }

    /**
     * 更新医护人员信息
     * @param staff 医护人员信息
     * @return 操作结果
     */
    @Operation(summary = "更新医护人员", description = "根据ID更新医护人员信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "医护人员信息更新成功"),
        @ApiResponse(responseCode = "400", description = "医护人员ID不能为空或已存在相同手机号的医护人员"),
        @ApiResponse(responseCode = "404", description = "未找到该医护人员")
    })
    @PutMapping
    public R<String> updateMedicalStaff(@RequestBody MedicalStaff staff) {
        // 检查是否存在
        if (staff.getStaffId() == null) {
            return R.failure(400, "医护人员ID不能为空");
        }

        MedicalStaff existingStaff = medicalStaffService.getById(staff.getStaffId());
        if (existingStaff == null) {
            return R.failure(404, "未找到该医护人员");
        }

        // 检查是否已存在相同手机号的其他医护人员
        LambdaQueryWrapper<MedicalStaff> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MedicalStaff::getPhone, staff.getPhone())
                   .ne(MedicalStaff::getStaffId, staff.getStaffId());
        MedicalStaff duplicateStaff = medicalStaffService.getOne(queryWrapper);

        if (duplicateStaff != null) {
            return R.failure(400, "已存在相同手机号的医护人员");
        }

        medicalStaffService.updateById(staff);
        return R.success("医护人员信息更新成功");
    }

    /**
     * 删除医护人员
     * @param staffId 医护人员ID
     * @return 操作结果
     */
    @Operation(summary = "删除医护人员", description = "根据ID删除医护人员")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "医护人员删除成功"),
        @ApiResponse(responseCode = "404", description = "未找到该医护人员")
    })
    @DeleteMapping("/{staffId}")
    public R<String> deleteMedicalStaff(@Parameter(description = "医护人员ID") @PathVariable Integer staffId) {
        // 检查是否存在
        MedicalStaff existingStaff = medicalStaffService.getById(staffId);
        if (existingStaff == null) {
            return R.failure(404, "未找到该医护人员");
        }

        // 执行删除操作
        medicalStaffService.removeById(staffId);
        return R.success("医护人员删除成功");
    }

    /**
     * 更新医护人员状态（在职/离职）
     * @param staffId 医护人员ID
     * @param status 状态（0-离职，1-在职）
     * @return 操作结果
     */
    @Operation(summary = "更新医护人员状态", description = "更新医护人员的在职/离职状态")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "医护人员状态更新成功"),
        @ApiResponse(responseCode = "400", description = "状态值无效，应为0（离职）或1（在职）"),
        @ApiResponse(responseCode = "404", description = "未找到该医护人员")
    })
    @PutMapping("/{staffId}/status")
    public R<String> updateStaffStatus(
            @Parameter(description = "医护人员ID") @PathVariable Integer staffId,
            @Parameter(description = "状态值：0-离职，1-在职") @RequestParam Integer status) {

        if (status != 0 && status != 1) {
            return R.failure(400, "状态值无效，应为0（离职）或1（在职）");
        }

        MedicalStaff staff = medicalStaffService.getById(staffId);
        if (staff == null) {
            return R.failure(404, "未找到该医护人员");
        }

        staff.setStatus(status);
        medicalStaffService.updateById(staff);

        String statusText = status == 1 ? "在职" : "离职";
        return R.success("医护人员状态已更新为" + statusText);
    }
}
